from flask import Flask,render_template,request,flash
import pandas as pd
import numpy as np
from sklearn import metrics
from sklearn.linear_model import LinearRegression, RidgeCV, LassoCV,ElasticNetCV
import matplotlib.pyplot as plt
import matplotlib as mpl
import warnings
warnings.filterwarnings("ignore")


def linearregression(user):
    data = pd.read_csv("prostate_data.txt", sep="\t")
    data = data.drop(['Unnamed: 0'], axis=1)
    # 分割训练集和测试集
    y_train = np.array(data[data.train == "T"]['lpsa'])
    X_train = np.array(data[data.train == "T"].drop(['lpsa', 'train'], axis=1))  # x参数可删去序号，y值，和是否为训练集
    linreg_model = LinearRegression(normalize=True).fit(X_train, y_train)#训练样本
    user=np.array(user)
    testhome=[]
    testhome.append(user)
    testhome=np.array(testhome)
    y = linreg_model.predict(testhome)
    return y

def ridgeregression(user):
    data = pd.read_csv("prostate_data.txt", sep="\t")
    data = data.drop(['Unnamed: 0'], axis=1)
    # 分割训练集和测试集
    y_train = np.array(data[data.train == "T"]['lpsa'])
    X_train = np.array(data[data.train == "T"].drop(['lpsa', 'train'], axis=1))
    ridge_cv = RidgeCV(normalize=True, alphas=np.logspace(-10, 1, 400))
    ridge_model = ridge_cv.fit(X_train, y_train)
    user = np.array(user)
    testhome = []
    testhome.append(user)
    testhome = np.array(testhome)
    y = ridge_model.predict(testhome)
    return y

def lassoregression(user):
    data = pd.read_csv("prostate_data.txt", sep="\t")
    data = data.drop(['Unnamed: 0'], axis=1)
    # 分割训练集和测试集
    y_train = np.array(data[data.train == "T"]['lpsa'])
    X_train = np.array(data[data.train == "T"].drop(['lpsa', 'train'], axis=1))
    lasso_cv = LassoCV(normalize=True, alphas=np.logspace(-10, 1, 400))
    lasso_model = lasso_cv.fit(X_train, y_train)
    user = np.array(user)
    testhome = []
    testhome.append(user)
    testhome = np.array(testhome)
    y = lasso_model.predict(testhome)
    return y

def lassoregression(user):
    data = pd.read_csv("prostate_data.txt", sep="\t")
    data = data.drop(['Unnamed: 0'], axis=1)
    # 分割训练集和测试集
    y_train = np.array(data[data.train == "T"]['lpsa'])
    X_train = np.array(data[data.train == "T"].drop(['lpsa', 'train'], axis=1))
    lasso_cv = LassoCV(normalize=True, alphas=np.logspace(-10, 1, 400))
    lasso_model = lasso_cv.fit(X_train, y_train)
    user = np.array(user)
    testhome = []
    testhome.append(user)
    testhome = np.array(testhome)
    y = lasso_model.predict(testhome)
    return y

def ElasticNet(user):
    data = pd.read_csv("prostate_data.txt", sep="\t")
    data = data.drop(['Unnamed: 0'], axis=1)
    # 分割训练集和测试集
    y_train = np.array(data[data.train == "T"]['lpsa'])
    X_train = np.array(data[data.train == "T"].drop(['lpsa', 'train'], axis=1))
    elastic_net_cv = ElasticNetCV(normalize=True, alphas=np.logspace(-10, 1, 400),
                                  l1_ratio=np.linspace(0, 1, 100))
    elastic_net_model = elastic_net_cv.fit(X_train, y_train)
    user = np.array(user)
    testhome = []
    testhome.append(user)
    testhome = np.array(testhome)
    y = elastic_net_model.predict(testhome)
    return y

app = Flask(__name__,static_url_path='')
app.secret_key='mtydnl'

@app.route('/',methods=['GET','POST'])
def hello_world():
    user=[]
    if request.method=='POST':
        lcavol=request.form.get('lcavol')
        lweight=request.form.get('lweight')
        age=request.form.get('age')
        lbph = request.form.get('lbph')
        svi = request.form.get('svi')
        lcp = request.form.get('lcp')
        gleason = request.form.get('gleason')
        pgg45 = request.form.get('pgg45')
        if not all([lcavol,lweight,age,lbph,svi,lcp,gleason,pgg45]):
            flash('参数不完整')
        else:
            user.append(lcavol)
            user.append(lweight)
            user.append(age)
            user.append(lbph)
            user.append(svi)
            user.append(lcp)
            user.append(gleason)
            user.append(pgg45)
            y0=linearregression(user)
            y1=ridgeregression(user)
            y2=lassoregression(user)
            y3 = ElasticNet(user)
            flash('线性回归的lpsa:{:.5f}'.format(y0[0]))
            flash('岭回归的lpsa:{:.5f}'.format(y1[0]))
            flash('lasso回归的lpsa:{:.5f}'.format(y2[0]))
            flash('弹性网络回归的lpsa:{:.5f}'.format(y3[0]))
    return render_template('index.html')


if __name__ == '__main__':
    app.run()
